/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import React, { useEffect, useRef, useState } from 'react';
import {
  View,
  Text,
  Image,
  StyleSheet,
  TouchableOpacity,
  FlatList,
  TextInput,
  StatusBar,
  Platform,
  Keyboard,
  TouchableHighlight,
} from 'react-native';
import { GridCol, GridRow, useBreakpointValue } from '@hadss/react_native_adaptive_layout/src';
import Secondary from './SecondaryPage.tsx';
import {
  NavigationSplitContainer,
  NavigationMode,
  NavBarPosition,
} from '@hadss/react_native_adaptive_layout';
import { messageData } from './mockData.ts'
import { MessageItem, RenderItemProps } from './type.ts'
const App = (props: any) => {
  const { changePage } = props
  useEffect(() => {
    if (Platform.OS === 'android') {
      StatusBar.setBackgroundColor('transparent', true)
      StatusBar.setTranslucent(true)
    }
  }, [])
  const currentBp = useBreakpointValue<string>({
    base: 'base',
    sm: 'sm',
    md: 'md',
    lg: 'lg',
    xl: 'xl',
  }) as string;
  const getWidthBar = useBreakpointValue({
    base: '0%',
    xs: '0%',
    sm: '0%',
    md: '0%',
    lg: '10%',
    xl: '10%',
  }) as string;
  const getWidthList = useBreakpointValue({
    base: '100%',
    xs: '100%',
    sm: '100%',
    md: '50%',
    lg: '40%',
    xl: '40%',
  }) as string;
  const getWidthDetail = useBreakpointValue({
    base: '100%',
    xs: '100%',
    sm: '100%',
    md: '50%',
    lg: '50%',
    xl: '50%',
  });
  const [activeItem, setActiveItem] = useState<MessageItem>({
    id: '1',
    name: '张晓萌',
    message: '好的，我明天过来',
    time: '13:55',
    avatar: require('../../../assets/images/touxiang.png'),
    unread: null,
  });
  const childRef = useRef<any>(null);// 创建ref引用
  const handlePress = (item: MessageItem) => {
    Keyboard.dismiss();
    childRef.current?.updateData(item); // 发送数据到子组件
    if (currentBp === 'sm' || currentBp === 'base') {
      childRef.current?.show();
    }
  };
  const ToolBar = () => (
    <View style={(currentBp === 'lg' || currentBp === 'xl') ? styles.bottomWrapLg : styles.bottomWrap}>
      <TouchableOpacity
        style={(currentBp === 'lg' || currentBp === 'xl') ? styles.bottomItemLg : styles.bottomItem}>
        <Image
          style={styles.bottomImg}
          source={require('../../../assets/images/xiaoxi.png')}
        />
        <Text style={styles.bottomTitleActive}>消息</Text>
      </TouchableOpacity>
      <TouchableOpacity
        style={(currentBp === 'lg' || currentBp === 'xl') ? styles.bottomItemLg : styles.bottomItem}>
        <Image
          style={styles.bottomImg}
          source={require('../../../assets/images/txl.png')}
        />
        <Text style={styles.bottomTitle}>通讯录</Text>
      </TouchableOpacity>
      <TouchableOpacity
        style={(currentBp === 'lg' || currentBp === 'xl') ? styles.bottomItemLg : styles.bottomItem}>
        <Image
          style={styles.bottomImg}
          source={require('../../../assets/images/sjq.png')}
        />
        <Text style={styles.bottomTitle}>社交圈</Text>
      </TouchableOpacity>
      <TouchableOpacity
        style={(currentBp === 'lg' || currentBp === 'xl') ? styles.bottomItemLg : styles.bottomItem}>
        <Image
          style={styles.bottomImg}
          source={require('../../../assets/images/my.png')}
        />
        <Text style={styles.bottomTitle}>我的</Text>
      </TouchableOpacity>
    </View>
  );
  const HomeScreen = () => {
    const renderItem = ({ item }: RenderItemProps) => (
      <TouchableHighlight
        onPress={(event) => {
          event.stopPropagation();
          handlePress(item);
        }}
        style={[
          activeItem.id === item.id && styles.itemActive,
          { marginLeft: 12, marginRight: 12, borderRadius: 16 },
        ]}
        underlayColor={'rgba(10, 89, 247,0.1)'}
        activeOpacity={0.1}>
        <View style={[styles.item]}>
          <View style={[styles.itemImgWrap]}>
            <Image style={styles.itemImg} source={item.avatar} />
            {item.unread && (
              <View
                style={
                  typeof item.unread === 'number'
                    ? styles.unreadBubbleFirstWrap
                    : styles.unreadBubbleSecondWrap
                }>
                <Text
                  style={
                    typeof item.unread === 'number'
                      ? styles.unreadBubbleFirst
                      : styles.unreadBubbleSecond
                  }>
                  {item.unread}
                </Text>
              </View>
            )}
          </View>
          <View style={styles.itemContent}>
            <Text style={styles.contentMain}>{item.name}</Text>
            <Text style={styles.contentSecondary}>{item.message}</Text>
          </View>
          <Text style={styles.itemTime}>{item.time}</Text>
        </View>
      </TouchableHighlight>
    );
    return (
      <>
        <StatusBar barStyle='dark-content' />
        <GridRow
          style={styles.gridRow}
          columns={12}>
          {/* 大屏侧边栏 */}
          {(currentBp === 'lg' || currentBp === 'xl') && (
            <GridCol
              style={{ width: getWidthBar }}
              offset={0}
              order={0}>
              <ToolBar></ToolBar>
            </GridCol>
          )}
          {/* 消息列表页 */}
          <GridCol
            style={{ width: getWidthList }}
            offset={0}
            order={0}>
            <View style={styles.container}>
              {/* Header */}
              <View style={styles.titleWrap}>
                <TouchableOpacity
                  onPress={(event) => {
                    event.stopPropagation();
                    changePage('Home');
                  }}>
                  <Text style={styles.title}>消息</Text>
                </TouchableOpacity>
                <View style={styles.iconWrap}>
                  {(currentBp === 'lg' || currentBp === 'xl')
                    ? (<View style={{ position: 'relative' }}>
                      <Image
                        style={styles.titleImgLg}
                        source={require('../../../assets/images/lg-search.png')}
                      />
                      <TextInput style={styles.input} placeholder='搜索...' />
                    </View>)
                    : (<Image
                      style={styles.titleImg}
                      source={require('../../../assets/images/search.png')}
                    />)}

                  <Image
                    style={[styles.titleImg, { marginLeft: 8 }]}
                    source={require('../../../assets/images/add.png')}
                  />
                </View>
              </View>

              <FlatList
                data={messageData}
                renderItem={renderItem}
                keyExtractor={item => item.id}
                style={styles.content}
                keyboardShouldPersistTaps='handled'
              />

              {/* Bottom */}
              {(currentBp === 'sm' || currentBp === 'md') && (
                <ToolBar></ToolBar>
              )}
            </View>
          </GridCol>
          {/* 详情页 */}
          {
            (currentBp === 'sm' || currentBp === 'base')
              ? (<Secondary
                activeItem={activeItem}
                ref={childRef}
              ></Secondary>)
              : (<GridCol
                style={{ width: getWidthDetail }}
                offset={0}
                order={0}>
                <Secondary
                  activeItem={activeItem}
                  ref={childRef}
                ></Secondary>
              </GridCol>)
          }
        </GridRow>
      </>
    );
  };
  return (
    <>
      <NavigationSplitContainer
        mode={NavigationMode.Stack}
        navBarPosition={NavBarPosition.Start}
        navBarWidth={400}
        navBarWidthRange={[240, 400]}
        minContentWidth={200}
      >
        <HomeScreen></HomeScreen>
      </NavigationSplitContainer>
    </>
  );
};

const styles = StyleSheet.create({
  gridRow: {
    width: '100%',
    height: '100%',
  },
  container: {
    flex: 1,
    backgroundColor: '#fff',
    minHeight: '100%',
    paddingTop: Platform.OS === 'ios' ? 44 : StatusBar.currentHeight
  },
  titleWrap: {
    height: 56,
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingHorizontal: 16,
    alignItems: 'center',
  },
  title: {
    color: 'rgba(0, 0, 0, 0.9)',
    fontSize: 26,
    fontWeight: '700',
  },
  iconWrap: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  titleImg: {
    width: 40,
    height: 40,
  },
  titleImgLg: {
    width: 16,
    height: 16,
    position: 'absolute',
    top: '50%',
    left: 10,
    transform: [{ translateY: -16 }],
  },
  content: {
    flex: 1,
  },
  contentMain: {
    color: 'rgba(0, 0, 0, 0.9)',
    fontSize: 16,
    marginBottom: 5
  },
  contentSecondary: {
    color: 'rgba(0, 0, 0, 0.6)',
    fontSize: 14,
  },
  item: {
    height: 72,
    flexDirection: 'row',
    alignItems: 'center',
  },
  itemActive: {
    backgroundColor: 'rgba(10, 89, 247,0.1)',
  },
  itemImgWrap: {
    position: 'relative',
  },
  itemImg: {
    width: 40,
    height: 40,
    margin: 18,
    borderRadius: 20,
  },
  itemContent: {
    flex: 1,
    justifyContent: 'center',
  },
  itemTime: {
    marginRight: 16,
    color: 'rgb(24, 36, 49)',
    fontSize: 12,
    opacity: 0.5,
  },
  unreadBubbleFirstWrap: {
    position: 'absolute',
    right: 16,
    top: 11,
    backgroundColor: '#FFF',
    width: 20,
    height: 20,
    borderRadius: 10,
    alignItems: 'center',
    justifyContent: 'center',
  },
  unreadBubbleFirst: {
    borderRadius: 8,
    backgroundColor: 'rgb(232, 72, 38)',
    color: 'rgb(255, 255, 255)',
    fontSize: 10,
    textAlign: 'center',
    width: 16,
    height: 16,
    lineHeight: 16,
  },
  unreadBubbleSecondWrap: {
    position: 'absolute',
    right: 10,
    top: 11,
    backgroundColor: '#FFF',
    width: 31,
    height: 20,
    borderRadius: 10,
    alignItems: 'center',
    justifyContent: 'center',
  },
  unreadBubbleSecond: {
    borderRadius: 8,
    backgroundColor: 'rgb(232, 72, 38)',
    fontSize: 10,
    textAlign: 'center',
    width: 27,
    height: 16,
    lineHeight: 16,
    color: '#fff',
  },

  bottomWrap: {
    flexDirection: 'row',
    backgroundColor: 'rgba(241, 243, 245, 0.8)',
    paddingVertical: 7,
    height: 76
  },
  bottomWrapLg: {
    flexDirection: 'column',
    height: '100%',
    backgroundColor: 'rgba(241, 243, 245, 0.8)',
    alignItems: 'center',
    justifyContent: 'center',
  },
  bottomImg: {
    width: 24,
    height: 24,
    marginBottom: 6,
  },
  bottomItem: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'flex-start',
  },
  bottomItemLg: {
    alignItems: 'center',
    justifyContent: 'center',
    height: '15%'
  },
  bottomTitle: {
    color: 'rgba(0, 0, 0, 0.6)',
    fontSize: 10,
  },
  bottomTitleActive: {
    color: 'rgb(10, 89, 247)',
    fontSize: 10,
  },
  input: {
    width: 200,
    height: 40,
    borderWidth: 0,
    borderRadius: 20,
    backgroundColor: 'rgba(0, 0, 0, 0.05)',
    paddingHorizontal: 36,
    paddingVertical: 0,
  },
});

export default App;
